package com.example.demo.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.File;
import java.io.IOException;

@Controller
public class DownFileController {
    @GetMapping("/downFile")
    public String downFile(){
        System.out.println("进入下载页面");
        return "down";
    }

    @GetMapping("/down")
    public ResponseEntity<byte[]> FileDown(String fileName){
        System.out.println("进入下载文件方法，下载文件名为："+fileName);
        String dirPath = "D:/file/";
        File file=new File(dirPath+File.separator+fileName);
        HttpHeaders headers=new HttpHeaders();
        headers.setContentDispositionFormData("attachment",fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (IOException e){
            System.out.println("下载文件出错,错误为："+e.getMessage());
            throw new RuntimeException(e);

        }

    }
}
